# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: static
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/7 13:49
@desc: 
========================================================================================================================
"""
import json
from functools import wraps

from addict import Dict
from sanic.response import json as JsonResponse
from sanic.response.types import JSONResponse
from sanic.views import HTTPMethodView

from config import config
from database.model.dept import SystemDeptDao, SystemDelEnum, SystemDept, SystemStatusEnum, SystemUserTypeEnum
from database.model.menu import SystemMenuDao, SystemMenu
from database.model.role import SystemRoleDao, SystemRoleMenuDao, SystemRole
from database.model.user import SystemUserDao, SystemUserRoleDao, SystemUser
from utils.myDataUtils import TreeBuilder
from utils.myEncrypt import HashCipher
from utils.myLog import SeqLog
from utils.myResFormat import ResultJson, ResultCode
from utils.mySnowflake import Sf

# 配置日志
seqLog = SeqLog().get_logger()


# 检验权限字符串的装饰器
def permAuth(perKey):
    def decorator(function):
        @wraps(function)
        async def decorated_function(*args, **kwargs):
            # 获取token中的用户权限
            user_info = {}
            for item in args:
                if hasattr(item, "headers"):
                    user_info = item.headers.user_info
            user_permissions = user_info.get("permissions", [])

            # 判断是否有权限
            if "*:*:*" in user_permissions or perKey in user_permissions:
                response = await function(*args, **kwargs)
                return response
            else:
                return JsonResponse(ResultJson(ret=ResultCode.PRE_AUTH_ERROR).result)

        return decorated_function

    return decorator


def response2json(response: JSONResponse) -> dict:
    return json.loads(response.body.decode())


class DeptListView(HTTPMethodView):
    """【系统部门】列表接口"""

    @permAuth("system:dept:list")
    async def get(self, request):
        deptName: str = request.args.get('deptName')
        status: str = request.args.get('status')

        condition = Dict()

        if deptName:
            condition.deptName = deptName

        if status:
            condition.status = status

        condition.delFlag = SystemDelEnum.p0.value

        data = await SystemDeptDao().find(condition=condition.to_dict(), sort_list=["orderNum"])

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)


class DeptCreateView(HTTPMethodView):
    @permAuth("system:dept:add")
    async def post(self, request):
        """【系统部门】新增部门"""

        data: Dict = request.json

        # 查询父级id信息
        parentData = await SystemDeptDao().find_one(condition=dict(deptId=str(data.get("parentId"))))

        # 生成父级数据
        data["ancestors"] = parentData.get("ancestors") + "," + parentData.get("deptId")
        data["deptId"] = Sf.generate()

        # 判断同一父级部门下不重名
        validation = {"deptName": data.get("deptName"), "deptId": data.get("parentId"), "delFlag": SystemDelEnum.p0.value, }
        isSuccess = await SystemDeptDao().insert_one(data=data, validation=validation)

        if isSuccess:
            return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)
        else:
            return JsonResponse(ResultJson(ret=ResultCode.DEPT_ERROR).result)

    @permAuth("system:dept:edit")
    async def put(self, request):
        """【系统部门】修改用户信息"""
        update: Dict = request.json

        updateAllow = SystemDept().dump(update)

        # 获取上级目录id
        deptData = await SystemDeptDao().find_one(condition=dict(deptId=update.get('deptId')))

        # 判断原始目录的父级id是否变化
        if deptData.get('parentId') == update.get('parentId'):
            await SystemDeptDao().update(condition=dict(deptId=update.get('deptId')), update=updateAllow)
        else:
            # 处理本条数据的上级关联关系
            parentId = update.get('parentId')
            parentData = await SystemDeptDao().find_one(condition=dict(deptId=parentId))
            repAncestors = parentData.get('ancestors') + "," + parentId

            # 修改所关联的下级目录的上级目录
            updateAllow['ancestors'] = repAncestors
            await SystemDeptDao().update(condition=dict(deptId=update.get('deptId')), update=updateAllow)

            # 处理下级关联的路径问题
            oldAncestors = deptData.get('ancestors') + "," + deptData.get('deptId')
            condition = {"ancestors": {"$regex": oldAncestors}}

            SystemDeptDataList = await SystemDeptDao().find(condition=condition)

            for item in SystemDeptDataList:
                ancestors = str(item.get('ancestors')).replace(oldAncestors, repAncestors + "," + deptData.get('deptId'))
                await SystemDeptDao().update(condition=dict(deptId=item.get('deptId'), delFlag=SystemDelEnum.p0.value), update=dict(ancestors=ancestors))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class DeptDetailView(HTTPMethodView):
    @permAuth("system:dept:query")
    async def get(self, request, deptId):
        """【系统部门】部门详情"""
        data = await SystemDeptDao().find_one(condition=dict(deptId=deptId, delFlag=SystemDelEnum.p0.value))
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)

    @permAuth("system:dept:remove")
    async def delete(self, request, deptId):
        """【系统部门】删除部门"""
        data = await SystemDeptDao().update(condition=dict(deptId=deptId), update=dict(delFlag=SystemDelEnum.p1.value))

        # 部门删除，去掉改部门已分配人员
        await SystemUserDao().update(condition=dict(deptId=deptId), update=dict(deptId=""))
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)


class DeptExcludeView(HTTPMethodView):

    async def get(self, request, deptId):
        """【系统部门】排除查询"""

        # 查询部门id不是指定id或者ancestors不包含该id,且状态未删除的数据
        condition = {"$and": [{"deptId": {"$ne": deptId}}, {"ancestors": {"$not": {"$regex": deptId}}}], "delFlag": SystemDelEnum.p0.value,
                     "status": SystemStatusEnum.p0.value, }
        data = await SystemDeptDao().find(condition=condition)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)


class RoleListView(HTTPMethodView):
    """【系统角色】列表接口"""

    @permAuth("system:role:list")
    async def get(self, request):
        pageNum: str = request.args.get('pageNum', 1)
        pageSize: str = request.args.get('pageSize', 0)
        roleName: str = request.args.get('roleName')
        roleKey: str = request.args.get('roleKey')
        status: str = request.args.get('status')

        condition = Dict()

        if roleName:
            condition.roleName = roleName

        if roleKey:
            condition.roleKey = roleKey

        if status:
            condition.status = status

        condition.roleAdmin = False
        condition.delFlag = SystemDelEnum.p0.value

        data = await SystemRoleDao().find(condition=condition.to_dict(), page=int(pageNum), size=int(pageSize), total_count=True, sort_list=['roleSort'])

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)


class RoleCreateView(HTTPMethodView):
    """【系统角色】新增接口"""

    @permAuth("system:role:add")
    async def post(self, request):
        data: Dict = request.json

        # 生成父级数据
        data["roleId"] = Sf.generate()

        # 判断角色名称和权限字符不能重复
        validation = {
            "$or": [{"roleKey": data.get("roleKey"), "delFlag": SystemDelEnum.p0.value}, {"roleName": data.get("roleName"), "delFlag": SystemDelEnum.p0.value}]}
        isSuccess = await SystemRoleDao().insert_one(data=data, validation=validation)

        if isSuccess:
            return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)
        else:
            return JsonResponse(ResultJson(ret=ResultCode.ROLE_ERROR).result)

    @permAuth("system:role:edit")
    async def put(self, request):
        """【系统角色】修改信息"""
        update: Dict = request.json
        updateAllow = SystemRole().dump(update)
        await SystemRoleDao().update(condition=dict(roleId=update.get("roleId")), update=updateAllow)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class RoleStatusView(HTTPMethodView):

    async def put(self, request):
        """【系统角色】修改状态"""
        update: Dict = request.json

        await SystemRoleDao().update(condition=dict(roleId=update.get("roleId")), update=update)

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class RoleDetailView(HTTPMethodView):
    @permAuth("system:role:query")
    async def get(self, request, roleId: str):
        """【系统角色】获取角色信息"""

        roleData = await SystemRoleDao().find_one(condition=dict(roleId=roleId))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=roleData).result)

    @permAuth("system:role:remove")
    async def delete(self, request, roleId: str):
        """【系统角色】获取删除角色信息"""

        # 分割路径的roleId,变为list
        condition = {"roleId": {"$in": roleId.split(',')}}
        await SystemRoleDao().update(condition=condition, update=dict(delFlag=SystemDelEnum.p1.value))

        # 删除人员的绑定关系
        await SystemUserRoleDao().delete(condition=condition)

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class AuthUserAllocatedListView(HTTPMethodView):
    async def get(self, request):
        """【系统角色】给角色分配人员"""
        pageNum: str = request.args.get('pageNum')
        pageSize: str = request.args.get('pageSize')
        roleId: str = request.args.get('roleId')
        username: str = request.args.get('username')
        phone: str = request.args.get('phone')

        # 组装查询条件
        UserRoleIds = await SystemUserRoleDao().find(condition=dict(roleId=roleId))

        condition = Dict()
        if username:
            condition.username = username

        if phone:
            condition.phone = phone

        condition.userId = {"$in": [item.get("userId") for item in UserRoleIds]}
        condition.delFlag = SystemDelEnum.p0.value
        condition.userType = SystemUserTypeEnum.p0.value

        # 组装人员的部门信息
        userData = await SystemUserDao().find(condition=condition.to_dict(), page=int(pageNum), size=int(pageSize), sort_list=["create_time"], total_count=True)
        for item in userData.get("data", []):
            item["dept"] = await SystemDeptDao().find_one(condition=dict(deptId=item.get('deptId')))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=userData).result)


class AuthUserUnallocatedListView(HTTPMethodView):
    async def get(self, request):
        """【系统角色】获取未授权用户列表"""
        pageNum: str = request.args.get('pageNum')
        pageSize: str = request.args.get('pageSize')
        roleId: str = request.args.get('roleId')
        username: str = request.args.get('username')
        phone: str = request.args.get('phone')

        # 组装查询条件
        UserRoleIds = await SystemUserRoleDao().find(condition=dict(roleId=roleId))

        condition = Dict()
        if username:
            condition.username = username

        if phone:
            condition.phone = phone

        condition.userId = {"$nin": [item.get("userId") for item in UserRoleIds]}
        condition.delFlag = SystemDelEnum.p0.value
        condition.userType = SystemUserTypeEnum.p0.value

        # 组装人员的部门信息
        userData = await SystemUserDao().find(condition=condition.to_dict(), page=int(pageNum), size=int(pageSize), sort_list=["create_time"], total_count=True)
        for item in userData.get("data", []):
            item["dept"] = await SystemDeptDao().find_one(condition=dict(deptId=item.get('deptId')))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=userData).result)


class AuthUserSelectAllView(HTTPMethodView):
    async def put(self, request):
        """【系统角色】批量绑定角色人员"""
        roleId: str = request.args.get('roleId')
        userIds: str = request.args.get('userIds')
        userIdList = userIds.split(',')

        # 批量插入用户关系
        data = [dict(userId=userId, roleId=roleId) for userId in userIdList]
        await SystemUserRoleDao().insert_many(collection_list=data)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class AuthUserCancelView(HTTPMethodView):
    async def put(self, request):
        """【系统角色】取消角色人员授权"""

        update: Dict = request.json
        await SystemUserRoleDao().delete(condition=update)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class AuthUserCancelAllView(HTTPMethodView):
    async def put(self, request):
        """【系统角色】批量取消角色人员授权"""

        roleId: str = request.args.get('roleId')
        userIds: str = request.args.get('userIds')

        # 判断是批量删除还是单个删除
        condition = {"roleId": roleId, "userId": {"$in": userIds.split(",")}}

        await SystemUserRoleDao().delete(condition=condition)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class UserListView(HTTPMethodView):

    @permAuth("system:user:list")
    async def get(self, request):
        """【系统用户】列表接口"""
        pageNum: str = request.args.get('pageNum')
        pageSize: str = request.args.get('pageSize')
        deptId: str = request.args.get('deptId')
        username: str = request.args.get('username')
        phone: str = request.args.get('phone')
        status: str = request.args.get('status')

        # 条件查询
        condition = Dict()

        if deptId:
            # 上级的
            deptData = await SystemDeptDao().find(condition={"ancestors": {"$regex": deptId}})
            deptIds = tuple([item["deptId"] for item in deptData])
            condition.deptId = {"$in": [deptId, *deptIds]}

        if username:
            condition.username = username

        if phone:
            condition.phone = phone

        if status:
            condition.status = status

        condition.delFlag = SystemDelEnum.p0.value

        # 只查询系统用户（不查询管理员账号）
        condition.userType = SystemUserTypeEnum.p0.value

        # 组装人员的部门信息
        userData = await SystemUserDao().find(condition=condition.to_dict(), page=int(pageNum), size=int(pageSize), sort_list=["create_time"], total_count=True)
        for item in userData.get("data", []):
            item["dept"] = await SystemDeptDao().find_one(condition=dict(deptId=item.get('deptId')))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=userData).result)


class UserDeptTreeView(HTTPMethodView):

    @classmethod
    def deptFormat(cls, SystemDeptList):
        container = []
        for item in SystemDeptList:
            deptItem = {"id": item.get("deptId"), "parentId": item.get("parentId"), "label": item.get("deptName"), }
            container.append(deptItem)
        return container

    async def get(self, request):
        """【系统用户】部门的结构树"""

        # 查询全部数据
        condition = dict(delFlag=SystemDelEnum.p0.value, status=SystemStatusEnum.p0.value)
        SystemDeptList = await SystemDeptDao().find(condition=condition)

        # 组装前端所需要的数据结构
        DeptList = self.deptFormat(SystemDeptList)

        # 组装成树的结构
        TreeData = TreeBuilder(DeptList).build(parentKey="parentId", ownerKey="id", topParent="0")
        TreeDataList = list(TreeData.values())

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=TreeDataList).result)


class UserStatusView(HTTPMethodView):
    @permAuth("*:*:*")
    async def put(self, request):
        """【系统用户】修改用户状态"""
        update: Dict = request.json

        await SystemUserDao().update(condition=dict(userId=update.get("userId")), update=update)

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class UserCreateView(HTTPMethodView):

    @permAuth("*:*:*")
    async def post(self, request):
        """【系统用户】新增接口"""
        data: Dict = request.json

        # 生成useId
        userId = Sf.generate()

        # 判断用户名是否重复
        condition = {"username": data.get("username"), "delFlag": SystemDelEnum.p0.value}
        isExist = await SystemUserDao().find_one(condition=condition)
        if isExist:
            return JsonResponse(ResultJson(ret=ResultCode.USER_ERROR).result)

        # 处理角色用户关系
        roleIds = data.pop("roleIds", [])
        for roleId in roleIds:
            await SystemUserRoleDao().insert_one(data=dict(roleId=roleId, userId=userId))

        # 用户表插入数据
        user_info = request.headers.user_info
        username = user_info.get('user', {}).get('username')
        data["userId"] = userId
        data["createBy"] = username
        data["password"] = HashCipher.md5(config.ENCRYPT_STRING + str(data.get('password', "")))
        await SystemUserDao().insert_one(data=data)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)

    @permAuth("*:*:*")
    async def put(self, request):
        """【系统用户】修改信息"""
        # 处理角色用户关系
        data: Dict = request.json

        userId = data.get('userId')
        roleIds = data.pop("roleIds", [])

        # 删除以前的角色人员关系，在增加新的关系
        await SystemUserRoleDao().delete(condition=dict(userId=userId))
        for roleId in roleIds:
            await SystemUserRoleDao().insert_one(data=dict(roleId=roleId, userId=userId))

        updateAllow = SystemUser().dump(data)
        await SystemUserDao().update(condition=dict(userId=userId), update=updateAllow)

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)

    @permAuth("*:*:*")
    async def get(self, request):
        """【系统用户】获取现有的角色列表"""
        res = Dict()
        condition = dict(status=SystemStatusEnum.p0.value, delFlag=SystemDelEnum.p0.value, roleAdmin=False)
        res.roles = await SystemRoleDao().find(condition=condition)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=res).result)


class UserDetailView(HTTPMethodView):

    @permAuth("system:user:query")
    async def get(self, request, userId: str):
        """【系统用户】获取用户信息"""
        res = Dict()

        userData = await SystemUserDao().find_one(condition=dict(userId=userId))

        # 找到用户绑定的角色id
        userRoleData = await SystemUserRoleDao().find(condition=dict(userId=userId))
        roleIds = [item.get("roleId") for item in userRoleData]

        condition = {"status": SystemStatusEnum.p0.value, "roleAdmin": False, "delFlag": SystemDelEnum.p0.value}
        roles = await SystemRoleDao().find(condition=condition)

        # 组装数据
        res.user = userData
        res.roleIds = roleIds
        res.roles = roles
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=res).result)

    @permAuth("system:user:remove")
    async def delete(self, request, userId: str):
        """【系统用户】获取删除用户信息"""

        # 分割路径的userId,变为list
        condition = {"userId": {"$in": userId.split(',')}}
        await SystemUserDao().update(condition=condition, update=dict(delFlag=SystemDelEnum.p1.value))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class UserProfileView(HTTPMethodView):

    async def get(self, request):
        """【个人中心】获取信息"""
        user_info = request.headers.user_info
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=user_info).result)

    async def put(self, request):
        """【个人中心】修改"""
        update: Dict = request.json
        user_info = request.headers.user_info
        userId = user_info.get('user', {}).get('userId')
        await SystemUserDao().update(condition=dict(userId=userId), update=update)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class UserProfileAvatarView(HTTPMethodView):

    async def post(self, request):
        """【个人中心】修改头像"""
        avatar = request.files.get("avatarfile")
        user_info = request.headers.user_info
        userId = user_info.get('user', {}).get('userId')

        # TODO: 上传头像文件流，生成一个url，更新用户信息的头像字段（没有obs， 功能未实现）

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=user_info).result)


class UserResetPwdView(HTTPMethodView):

    @permAuth("*:*:*")
    async def put(self, request):
        """【系统用户】重置密码/ 需要管理员权限"""
        data: Dict = request.json
        # 修改密码
        password = HashCipher.md5(config.ENCRYPT_STRING + str(data.get('password')))
        await SystemUserDao().update(condition=dict(userId=data.get('userId')), update=dict(password=password))
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class UserUpdatePwdView(HTTPMethodView):

    async def put(self, request):
        """【系统用户】更新密码"""
        oldPassword = request.args.get('oldPassword')
        newPassword = request.args.get('newPassword')
        user_info = request.headers.user_info

        # 判断旧密码是否正确
        userId = user_info.get('user', {}).get('userId', "")

        # 对密码进行加密
        old_encrypt_password = HashCipher.md5(config.ENCRYPT_STRING + str(oldPassword))
        new_encrypt_password = HashCipher.md5(config.ENCRYPT_STRING + str(newPassword))

        userData = await SystemUserDao().find_one(condition=dict(password=old_encrypt_password, userId=userId))

        if not userData:
            return JsonResponse(ResultJson(ret=ResultCode.PASSWORD_ERROR).result)
        else:
            await SystemUserDao().update(condition=dict(userId=userId), update=dict(password=new_encrypt_password))
            return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class AuthRoleView(HTTPMethodView):

    async def get(self, request, userId: str):
        """【系统用户】查询角色映射关系"""
        # 查询用户信息
        userData = await SystemUserDao().find_one(condition=dict(userId=userId))

        # 查询用户角色映射关系
        roleData = []
        userRoleList = await SystemUserRoleDao().find(condition=dict(userId=userId))

        # 查询角色信息
        for userRole in userRoleList:
            roleItem = await SystemRoleDao().find_one(condition=dict(roleId=userRole.get("roleId")))
            roleData.append(roleItem)

        # 组装返回数据
        resData = dict(user=userData, roles=roleData)
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=resData).result)

    async def put(self, request):
        """【系统用户】修改角色映射关系"""
        userId = request.args.get("userId")
        roleIds = request.args.get("roleIds")
        roleIds = roleIds.split(",")

        # 删除以前的角色人员关系，在增加新的关系
        await SystemUserRoleDao().delete(condition=dict(userId=userId))
        for roleId in roleIds:
            await SystemUserRoleDao().insert_one(data=dict(roleId=roleId, userId=userId))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=None).result)


class MenuDetailView(HTTPMethodView):

    @permAuth("system:menu:query")
    async def get(self, request, menuId: str):
        """【系统用户】查询"""
        menuData = await SystemMenuDao().find_one(condition=dict(menuId=menuId))
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=menuData).result)

    @permAuth("system:menu:remove")
    async def delete(self, request, menuId: str):
        """【系统用户】删除"""

        # 删除目录信息
        await SystemMenuDao().delete(condition=dict(menuId=menuId))

        # 删除角色目录映射
        await SystemRoleMenuDao().delete(condition=dict(menuId=menuId))

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class MenuListView(HTTPMethodView):

    @permAuth("system:menu:list")
    async def get(self, request):
        """【系统目录】列表"""
        menuName: str = request.args.get('menuName')
        status: str = request.args.get('status')

        # 条件查询
        condition = Dict()

        if menuName:
            condition.menuName = menuName

        if status:
            condition.status = status

        condition.visible = SystemDelEnum.p0.value

        # 查询数据列表
        MenuData = await SystemMenuDao().find(condition=condition.to_dict(), sort_list=['orderNum'])

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=MenuData).result)


class MenuCreateView(HTTPMethodView):

    @permAuth("system:menu:add")
    async def post(self, request):
        """【系统目录】新增"""
        data: Dict = request.json

        # 生成父级数据
        data["menuId"] = Sf.generate()

        # 判断同一级id不重名
        validation = {"parentId": data.get("parentId"), "menuName": data.get("menuName"), }
        isSuccess = await SystemMenuDao().insert_one(data=data, validation=validation)

        if isSuccess:
            return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=data).result)
        else:
            return JsonResponse(ResultJson(ret=ResultCode.MENU_ERROR).result)

    @permAuth("system:menu:edit")
    async def put(self, request):
        """【系统目录】修改"""
        update: Dict = request.json

        updateAllow = SystemMenu().dump(update)

        await SystemMenuDao().update(condition=dict(menuId=update.get('menuId')), update=updateAllow)

        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS).result)


class MenuTreeSelectView(HTTPMethodView):
    """【系统目录】树选择"""

    @classmethod
    def MenuFormat(cls, MenuData):
        container = []
        for item in MenuData:
            deptItem = {"id": item.get("menuId"), "parentId": item.get("parentId"), "label": item.get("menuName"), }
            container.append(deptItem)
        return container

    async def get(self, request):
        filter_fields = ['menuName', 'parentId', 'menuId']
        MenuData = await SystemMenuDao().find(condition=dict(status=SystemStatusEnum.p0.value), field=filter_fields)

        # 组装前端所需要的数据结构
        MenuList = self.MenuFormat(MenuData)

        # 组装成树的结构
        TreeData = TreeBuilder(MenuList).build(parentKey="parentId", ownerKey="id", topParent="0")
        TreeDataList = list(TreeData.values())
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=TreeDataList).result)


class MenuRoleTreeSelectView(HTTPMethodView):

    async def get(self, request, roleId: str):
        """【系统目录】已经选择树选择器"""
        res = Dict()

        # 查询树的列表
        TreeDataListResponse = await MenuTreeSelectView().get(request)
        TreeDataList = response2json(TreeDataListResponse).get("data", [])

        # 查询选中数据的
        roleData = await SystemRoleDao().find_one(condition=dict(roleId=roleId))

        res.menus = TreeDataList
        res.checkedKeys = roleData.get("menuIds", [])
        return JsonResponse(ResultJson(ret=ResultCode.SUCCESS, data=res.to_dict()).result)
